<template>
  <router-view />
  <loader />
</template>

<script setup name="app">
import {onMounted, watch, onBeforeMount, onBeforeUnmount} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import other from '@/utils/other';
import bus from '@/store/bus';
import Loader from '@/lui/loader.vue';
import tool from '@/utils/tool';
// 定义变量内容
const route = useRoute()
const router = useRouter()
const reload = () => {
  let cacheDate = tool.data.get('cacheDate')
  let freshCount = tool.data.get('freshCount')
  if(cacheDate) {
    if(cacheDate !== tool.getDay()) {
      if(freshCount) {
        tool.data.set('freshCount', freshCount + 1)
      }
      else {
        freshCount = 1
        tool.data.set('freshCount', freshCount)
      }
      if(freshCount < 2) {
        setTimeout(() => {
          window.location.reload()
        }, 100)
      } else {
        tool.data.set('cacheDate', tool.getDay())
      }
    }
  }
  else {
    if(freshCount) {
      tool.data.set('freshCount', freshCount + 1)
    }
    else {
      freshCount = 1
      tool.data.set('freshCount', freshCount)
    }
    if(freshCount < 2) {
      setTimeout(() => {
        tool.suc('系统更新中。。。')
        window.location.reload()
      }, 100)
    }
    else {
      tool.data.set('cacheDate', tool.getDay())
    }
  }
}
const updateVer = () => {
  // setTimeout(() => {
  //   if(route.name !== 'assist') {
  //     tool.post('app/getUpdateInfo').then(ret => {
  //       if(ret.stat) {
  //         tool.updateVer()
  //       }
  //     })
  //   }
  // }, 1000)
}
const scanCode = () => {
	let str = '';
	document.onkeydown = function (e) {
		if (e.target.tagName !== 'BODY') {
			str = '';
		} else {
			if (e.key !== 'Enter') {
				if (['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-'].indexOf(e.key) !== -1) {
					let k = e.key;
					str += k;
				}
			} else {
				if (str) {
					if (!str) return;
					let bill = str.split('-');
					if (bill.length !== 2) return;
					scanRet(str);
				}
				str = '';
			}
		}
	}
}
const scanRet = (str) => {
	if (!str) return tool.err('未读取到数据')
  bus.$emit('scan-ret', { code: str })
}
const openPage = ({row, field}) => {
  tool.post('page/getRouteByField', {
    field,
    routeName: route.name,
    value: row[field],
    row,
  }).then(ret => {
        if(ret.stat) {
          let routeName = ret.data.name
          tool.data.set('query', ret.data.query)
          setTimeout(() => {
            router.push({name: routeName, query:{billNo: ret.data.query.billNo}})
          }, 10)
        }
      })
}
const gotoPage = (obj) => {
  router.push({name: obj.routeName, query: obj.data})
}

// 监听路由的变化，设置网站标题
watch(
	() => route.path,
	() => {
		other.useTitle()
	},
	{
		deep: true,
	}
)
onBeforeMount (() => {
  reload()
})
// 页面加载时
onMounted(() => {
  scanCode()
  updateVer()
  bus.$on('openPage', openPage)
  bus.$on('gotoPage', gotoPage)
})
onBeforeUnmount(() => {
  bus.$off('openPage', openPage)
  bus.$off('gotoPage', gotoPage)
})


</script>